package com.powerunion.datacollection.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.powerunion.datacollection.common.SystemException;
import com.powerunion.datacollection.dao.CategoryRolesDao;
import com.powerunion.datacollection.dao.ColumnDao;
import com.powerunion.datacollection.dao.DaoException;
import com.powerunion.datacollection.dao.DaoFactory;
import com.powerunion.datacollection.model.CategoryRoles;
import com.powerunion.datacollection.model.Column;
import com.powerunion.datacollection.model.jsonObject.JSONDataBean;

import com.powerunion.util.log.LogHelper;

public class CategoryRolesManager {
	private static Logger logger = LogHelper.getInstance().getLogger(CategoryRolesManager.class);
	private CategoryRolesDao dao = null;
	public CategoryRolesManager() {
		super();
		this.dao = (CategoryRolesDao)DaoFactory.getInstance().getDao(CategoryRolesDao.class);
	}
	
	public boolean save(String saveStr,String roles) throws Exception{
		//参数为空
		if(StringUtils.isEmpty(saveStr)) {
			String[] args = { "saveStr" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter saveStr NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		
		//参数为空
		if(roles == null ||roles.length()<1) {
			String[] args = { "roles" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter roles NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		
		String[] roleIds = StringUtils.split(roles, ",");
		CategoryRoles cr = (CategoryRoles)JSONObject.toBean(JSONObject.fromObject(saveStr), CategoryRoles.class);
		
		//先删除原有的信息
		this.dao.delete(cr.getCategoryId(),cr.getPermissonType());
		
		return this.dao.save(cr,roleIds);
	}
	
	public JSONArray getRolesByCatetoryId(String categoryId,int permissionType) throws DaoException {
		//参数为空
		if(StringUtils.isEmpty(categoryId)) {
			String[] args = { "categoryId" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter categoryId NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		
		List list = this.dao.getRolesByCatetoryId(categoryId, permissionType);
		JSONArray jSONArray = JSONArray.fromObject(list);
		return jSONArray;
		
	}

	
	
}
